package com.my.netty.optimize.client;

import com.my.netty.optimize.client.handler.RpcResponseMessageHandler;
import com.my.netty.optimize.message.RpcRequestMessage;
import com.my.netty.optimize.protocol.MessageCodecSharable;
import com.my.netty.optimize.protocol.ProtocolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * 第一版rpc client只用于测试网络通信
 */
@Slf4j
public class RpcClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable messageSharableCodec = new MessageCodecSharable();

        // PRC 请求消息处理器
        RpcResponseMessageHandler rpcResponseMessageHandler = new RpcResponseMessageHandler();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProtocolFrameDecoder());
                    ch.pipeline().addLast(loggingHandler);
                    ch.pipeline().addLast(messageSharableCodec);
                    ch.pipeline().addLast(rpcResponseMessageHandler);
                }
            });
            Channel channel = bootstrap.connect(new InetSocketAddress("localhost", 8080)).sync().channel();

            //发送消息，进行RPC调用
            RpcRequestMessage requestMessage = new RpcRequestMessage();
            requestMessage.setSequenceId(1);
            requestMessage.setInterfaceName("com.my.netty.optimize.server.service.HelloService");
            requestMessage.setMethodName("sayHello");
            requestMessage.setParameterTypes(new Class[]{String.class});
            requestMessage.setParameterValue(new Object[] {"服务器"});
            requestMessage.setReturnType(String.class);
            channel.writeAndFlush(requestMessage).addListener(promise -> {
                if (!promise.isSuccess()) {
                    log.error("error", promise.cause());
                }
            });

            //阻塞主线程直到连接关闭
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
